
import React,{Component,PropTypes} from 'react'
import TextInput from './TextInput'
import { Link } from 'react-router'
import Table from './Table'
import style from './addStore.css'
import {myAjax, ROOTURL} from './../publicAPI/publicAPI'
import SelectInput from './SelectInput'
class AreamanagerEditor extends Component {
    constructor(props, context) {
        super(props, context);

        // 存在密码保护问题
        this.state = {
            username: "",
            password: "",
            pwdAgain: "",
            oldPwd: "",
            delete: false,
            deleteId: -1,
            checkInput: "",
            hasBeenMounted: false,  //判断是否已经加载
            shops: [],
            showshop: false,
            adminId:0,
            selectContracts:[]
        };

        var url = ROOTURL + 'shop/search.api'
        fetch(url, {
            method : 'POST',
            mode: 'cors',
            body: JSON.stringify({
                "where":{"dd":[["eq",false]]}
            })
        }).then(res=>{
            if(res.ok){
                res.json().then(data=>{
                    console.log('--------')
                    console.log(data);
                    console.log(res);
                    console.log('--------')
                    this.setState({
                        shops:data
                    })
                })
            }else{
                res.json().then(data=>{
                    alert(data.msgl10n)
                })
            }
        })
    }

    componentWillMount(){

        if( this.props.params.id ){
            //根据id获取数据
            var d = {};
            var _this = this;
            var url = ROOTURL + 'user/general/instance.api?id='+ this.props.params.id;
            fetch(url,{
                method: "GET",
                header: 'application/json; charset=utf-8'
            }).then(res=>{
                if(res.ok){
                    console.log(res);
                    res.json().then(data=>{
                        d = {
                            username: data.dname,
                            hasBeenMounted: true
                        };

                        if (!this.state.hasBeenMounted && this.props.params.id)
                            _this.setState(d);
                    })
                }else {
                    res.json().then(data=>{
                    alert(data.msgl10n)
                })
                }
            })

        }

    }
    
    handleCreate(){
        var _this=this
        if (this.state.username == "") {
            this.setState(
                {checkInput: "请输入用户名"}
            )
        }  else if (this.state.password == "") {
            this.setState(
                {checkInput: "请输入密码"}
            );
        } else if (this.state.password != this.state.pwdAgain) {
            this.setState(
                {checkInput: "两次密码不相同！"}
            )
        } else {
            //save
            this.setState(
                {checkInput: ""}
            )
        
            var url = ROOTURL + 'user/region-admin/create.api?uname='+this.state.username+'&passwd='+this.state.password;
            var userinfo= JSON.parse(localStorage.getItem('userInfo'))
            var token=userinfo.token
            fetch(url,{
                method: "POST",
                mode: 'cors',
                headers: {
                    "X-Cafune-Authentication":"SECRET",
                    "X-Cafune-Session-Token":token
                },
            }).then(res=>{
                console.log(res)
                if(res.ok || res.status == 204){
                    res.json().then(data=>{
                        console.log(data);
                        this.setState({
                            showshop:true,
                            adminId:data.id
                        })
                       
                    })
                }else{

                    alert('保存失败');
                }
            })
        }
    }

    handleSave() {
        const paramsId = this.props.params.id;
        if (this.state.username == "") {
            this.setState(
                {checkInput: "请输入用户名"}
            )
        } else if (paramsId && this.state.oldPwd == "") {
            this.setState(
                {checkInput: "请输入原密码"}
            )
        } else if (this.state.password == "") {
            if (!paramsId)
                this.setState(
                  {checkInput: "请输入密码"}
                );
            else
                this.setState(
                     {checkInput: "请输入新密码"}
                );
        } else if (this.state.password != this.state.pwdAgain) {
            this.setState(
                {checkInput: "两次密码不相同！"}
            )
        } else {
            //save
            this.setState(
                {checkInput: ""}
            )

            var url = ROOTURL + 'user/auth/passwd/passwd.api?login='+this.state.username+'&pass='+this.state.oldPwd+'&newpass='+this.state.password;
            var userinfo= JSON.parse(localStorage.getItem('userInfo'))
            var token=userinfo.token
            fetch(url,{
                method: "POST",
                // mode: 'no-cors'
                mode: 'cors',
                headers: {
                    "X-Cafune-Authentication":"SECRET",
                    "X-Cafune-Session-Token":token
                },
                body: JSON.stringify({
                })
            }).then(res=>{
                if(res.ok || res.status == 204){
                    console.log(res);
                    alert("修改成功");
                    window.location.href = '/Areamanager';
                }else {
                    alert("修改失败:"+res.msg);
                    // window.location.href = '/AdministratorM';
                }
            })
        }
    }

    doDelete(){
        var _this = this;
        var url = ROOTURL + 'user/general/instance.api?id=' + this.props.params.id;
        fetch(url,{
            method: 'DELETE',
            mode: 'cors',
            body: JSON.stringify({})
        }).then(function (res) {
            if (res.ok){
                alert('删除成功');
                window.location.href = '/Areamanager'

            }else{
                console.log(res)
            }
        });
        this.setState({
            delete: !this.state.delete
        });
    }
    //复选框
    handleSelect(e) {
        let cId = e.target.value
        let isChecked = e.target.checked

        if(e.target.checked) {

            this.addshop(cId)
        } else {

            this.delectshop(cId)
        }
    }
    addshop(cId){
        var shopurl=ROOTURL+'region/assign/instance.api'
        var userinfo= JSON.parse(localStorage.getItem('userInfo'))
        var token=userinfo.token
        fetch(shopurl, {
            method : 'POST',
            mode: 'cors',
            headers: {
                "X-Cafune-Authentication":"SECRET",
                "X-Cafune-Session-Token":token
            },
            body: JSON.stringify({
                "shop":cId,
                "admin":this.state.adminId
            })
        }).then(res=>{
            if(res.ok){
                res.json().then(data=>{
                    console.log(data);
                    console.log(res);
                    var shoplist=[]
                    shoplist=this.state.selectContracts
                    shoplist.push(data)
                    this.setState({
                        selectContracts:shoplist
                    })
                })
            }else{
                alert('添加管辖门店失败');
            }
        })
    }

    delectshop(cId){
        var id
        this.state.selectContracts.map(function(e){
            if(e.shopId==cId)
                id=e.id
        })
        var shopurl=ROOTURL+'region/assign/instance.api?id='+id
        var userinfo= JSON.parse(localStorage.getItem('userInfo'))
        var token=userinfo.token
        fetch(shopurl, {
            method : 'DELETE',
            mode: 'cors',
            headers: {
                "X-Cafune-Authentication":"SECRET",
                "X-Cafune-Session-Token":token
            },
        }).then(res=>{
            if(res.ok){
                res.json().then(data=>{
                    console.log(data);
                    console.log(res);
                })
            }else{
                alert('删除管辖门店失败');
            }
        })
    }

    finishshop(){

        window.location.href = '/Areamanager'

    }

    tHead() {
        var data = [
            {name: ""},
            {name: "商店名称"},
        ];
        const _headArr = [];
        const _width = {
            "0": "25%",
            "1": "75%",
        };
        _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1"
                                                    key={index}>{item.name}</th>));
        return _headArr;
    }

    tBody() {
        var _this=this
        return this.state.shops.map(function(item){            
            return <tr key={item.id}>
                <td><input type="checkbox" value={item.id} 
                    onChange={(e) => _this.handleSelect(e)}/></td>
                <td>{item.dname}</td>
            </tr>          
        })
    }

    render() {
        const paramsId = this.props.params.id;
        return (
            <div className="right-wapper">
                <div className="wrap">

                    <div className={style["input_div"]}>
                        <label>用户名</label>
                        {!paramsId ?
                            <TextInput val={this.state.username} inputId="uname" placeHolder="请输入用户名"
                                       onChange={val=>{this.setState({username: val})}}/>
                            :
                            <span id="juname">{this.state.username}</span>}

                    </div>
                    {
                        paramsId ?
                        <div className={style["input_div"]}>
                            <label>原密码</label>
                            <TextInput val={this.state.oldPwd} type="password" inputId="uname" placeHolder="请输入密码"
                                       onChange={val=>{this.setState({oldPwd: val})}}/>
                        </div> : null
                    }

                    <div className={style["input_div"]} id="np">
                        <label>{paramsId ? "新密码" : "密码"}</label>
                        <TextInput val={this.state.password} type="password" inputId="newpass" placeHolder="请输入密码"
                                   onChange={val=>{this.setState({password: val})}}/>
                    </div>
                    <div className={style["input_div"]}>
                        <label>确认密码</label>
                        <TextInput val={this.state.pwdAgain} type="password" inputId="pass" placeHolder="请重新输入密码"
                                   onChange={val=>{this.setState({pwdAgain: val})}}/>
                    </div>

                    

                    { 
                        this.state.checkInput != "" ?
                        <span id="hint">{this.state.checkInput}</span> : null
                    }
                    {
                        paramsId ?<button id="submit" className={style["btn_blue"]} onClick={this.handleSave.bind(this)}>保存</button> :
                        <button id="submit" className={style["btn_blue"]} onClick={this.handleCreate.bind(this)}>下一步</button>
                    }

                    {
                        paramsId ? <button id="delete" className={style["btn_red"]} onClick={()=>this.setState({delete: !this.state.delete})}>删除</button> : null
                    }

                    <Link to="/Areamanager" >
                        <button id="back" className={style["btn_blue"]}>返回</button>
                    </Link>
                </div>

                { 
                    this.state.delete ?
                    <div id={style["msgDialog"]}>
                        <div className={style["msgDialog_div"]}><h3 id={style["msgDialog_title"]}>删除提示？</h3><p id={style["msgDialog_content"]}>
                            确认删除？</p>
                            <div className={style["msgDialog_button"]}>
                                <button id={style["msgDialog_yes"]} onClick={this.doDelete.bind(this)}>确定</button>
                                <button id={style["msgDialog_no"]}
                                        onClick={()=>this.setState({delete: !this.state.delete})}>
                                    取消
                                </button>
                            </div>
                        </div>
                    </div> : null
                }
                {
                    this.state.showshop?
                    <div className={style['shop_show']}>
                        <div className={style['shopshow_div']}>
                            <div className={style["Table_div"]}>
                                <h2 className={style['catagory_h2']}>
                                    <span className="cata-title">选择管辖门店</span>                       
                                </h2>
                                <div>
                                    <Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()}/>
                                </div>
                                <button className={style['Table_button']} onClick={this.finishshop.bind(this)}>完成</button>
                            </div>
                        </div>
                    </div>:null
                }
            </div>
        )
    }
}


export default AreamanagerEditor